package com.wzj.yygh.oss.controller.front;

import com.wzj.yygh.common.exception.YyghException;
import com.wzj.yygh.common.result.R;
import com.wzj.yygh.common.result.ResultCode;
import com.wzj.yygh.oss.service.FileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

@Api(tags = "阿里云文件管理")
@RestController
@RequestMapping("/front/oss/file")
public class FrontFileController {
    @Autowired
    private FileService fileService;

    @Value("${yygh.file.root.path}")
    private String filePath;


    @ApiOperation("文件上传")
    @PostMapping("upload")
    public R upload(MultipartFile file) {
        String uploadUrl = fileService.upload(file);
        return R.ok().message("文件上传成功").data("url",uploadUrl);
    }
    @ApiOperation("文件上传本地")
    @PostMapping("uploadLocal")
    public R fileUpload(@RequestParam("file") MultipartFile file) {
        //获取上传文件名称
        String filename = file.getOriginalFilename();
        assert filename != null;
        String newFileName = UUID.randomUUID().toString().replaceAll("-","") + filename.substring(filename.lastIndexOf("."));
        //得到文件保存的位置以及新文件名
        File dest = new File(filePath);
        //文件夹不存在则创建
        if (!dest.exists()) {
            dest.mkdirs();
        }

        try {
            //上传文件保存
            file.transferTo(new File(dest+ "/" +newFileName));
            //文件URL路径地址
            return R.ok().message("文件上传成功").data("url","http://127.0.0.1:8160/front/oss/file/download?name="+newFileName);

        } catch (IOException e) {
            throw new YyghException(ResultCode.ERROR,"文件上传失败",e);
        }
    }

    @ApiOperation("文件下载")
    @GetMapping("/download")
    public void download(HttpServletResponse response,String name) {
        try {
        //输入流，通过输入流读取文件内容
            FileInputStream fileInputStream = new FileInputStream(filePath+ "/" + name);
            //输出流 通过输出流将文件写回游览器 展示照片
            ServletOutputStream outputStream = response.getOutputStream();
            response.setContentType("image/jpeg");
            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = fileInputStream.read(bytes)) != -1) {
                outputStream.write(bytes,0,len);
                outputStream.flush();
            }
            //关闭资源
            outputStream.close();
            fileInputStream.close();
        } catch (Exception e) {
            throw new YyghException(ResultCode.ERROR,"文件未找到",e);
        }
    }

}
